package com.rc.saas.tenant.service.transfer;

import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayFundAccountQueryModel;
import com.alipay.api.domain.AlipayFundTransCommonQueryModel;
import com.alipay.api.domain.AlipayFundTransPayModel;
import com.alipay.api.domain.Participant;
import com.alipay.api.request.AlipayFundAccountQueryRequest;
import com.alipay.api.request.AlipayFundTransCommonQueryRequest;
import com.alipay.api.request.AlipayFundTransUniTransferRequest;
import com.alipay.api.response.AlipayFundAccountQueryResponse;
import com.alipay.api.response.AlipayFundTransCommonQueryResponse;
import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.common.base.HttpConstant;
import com.rc.saas.tenant.common.component.UidGenerator;
import com.rc.saas.tenant.common.constant.CommonConstant;
import com.rc.saas.tenant.common.utils.StringUtil;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.mapper.transfer.MemberRefundApplyMapper;
import com.rc.saas.tenant.mapper.transfer.TransferWaysMapper;
import com.rc.saas.tenant.model.acct.AcctWithdrawOrder;
import com.rc.saas.tenant.model.acct.TenantOperatorAcctSetting;
import com.rc.saas.tenant.model.member.MemberAccount;
import com.rc.saas.tenant.model.member.MemberAccountRecord;
import com.rc.saas.tenant.model.member.MemberInfo;
import com.rc.saas.tenant.model.operator.TenantOperator;
import com.rc.saas.tenant.model.pay.TenantPayment;
import com.rc.saas.tenant.model.pay.TenantPaymentExample;
import com.rc.saas.tenant.model.tenant.Tenant;
import com.rc.saas.tenant.model.tenant.TenantSetting;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.model.transfer.*;
import com.rc.saas.tenant.service.acct.AcctWithdrawOrderService;
import com.rc.saas.tenant.service.member.MemberAccountRecordService;
import com.rc.saas.tenant.service.member.MemberAccountService;
import com.rc.saas.tenant.service.member.MemberInfoService;
import com.rc.saas.tenant.service.order.OrderInfoService;
import com.rc.saas.tenant.service.pay.TenantPaymentService;
import com.rc.saas.tenant.service.tenant.TenantService;
import com.rc.saas.tenant.service.tenant.TenantSettingService;
import com.rc.saas.tenant.service.weixin.WxPayWalletService;
import com.rc.saas.tenant.transfers.alipay.config.AliPayConfig;
import com.rc.saas.tenant.transfers.alipay.vo.AlipayTransPayWalletVo;
import com.rc.saas.tenant.transfers.weixin.WxTransPayWalletVo;
import com.rc.saas.tenant.vo.transfer.MemberRefundApplyExportVo;
import com.rc.saas.tenant.vo.transfer.MemberRefundApplySearch;
import com.rc.saas.tenant.vo.transfer.MemberRefundApplyVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by Sven on 2021/08/14
 */
@Service
public class MemberRefundApplyServiceImpl implements MemberRefundApplyService {
    private static Logger logger = LogManager.getLogger(MemberRefundApplyServiceImpl.class);
    @Autowired
    private MemberRefundApplyMapper memberRefundApplyMapper;

    @Autowired
    private MemberAccountService memberAccountService;

    @Autowired
    private MemberAccountRecordService memberAccountRecordService;

    @Autowired
    private UidGenerator uidGenerator;

    @Autowired
    private AliPayConfig aliPayConfig;

    @Autowired
    private TransferOrderService transferOrderService;

    @Autowired
    private MemberInfoService memberInfoService;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private AcctWithdrawOrderService acctWithdrawOrderService;

    @Autowired
    private TenantService tenantService;

    @Autowired
    private TenantPaymentService tenantPaymentService;

    @Autowired
    private TransferWaysMapper transferWaysMapper;

    @Autowired
    private TenantSettingService tenantSettingService;

    @Autowired
    private WxPayWalletService wxPayWalletService;


    @Override
    public MemberRefundApplyMapper getMapper() {
        return memberRefundApplyMapper;
    }

    @Override
    public PageInfo<MemberRefundApplyVo> listPageMemberRefundApply(MemberRefundApplySearch memberRefundApplySearch) {
        PageHelper.startPage(memberRefundApplySearch.getOffset(), memberRefundApplySearch.getLimit());
        List<MemberRefundApplyVo> list = memberRefundApplyMapper.listPageMemberRefundApply(memberRefundApplySearch);
        return new PageInfo<MemberRefundApplyVo>(list);
    }

    @Override
    public TResponse updateMemberRefundApplyStatus(MemberRefundApply memberRefundApply, MemberAccount memberAccount, String status, MemberInfo memberInfo, Tenant tenant) {
        if ("3".equals(status)) {
            Date date = new Date();
            memberRefundApply.setStatus("4");
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            memberRefundApply.setPaymentTime(formatter.format(date));
            memberRefundApply.setLastUpdatedTime(date);
            memberRefundApplyMapper.updateByPrimaryKeySelective(memberRefundApply);

            String outTradeNo = uidGenerator.genWxTransferOutTradeNo(tenant.getTenantPrefix(), memberInfo.getMobile(), CommonConstant.MT_TRANSFER_PREFIX);
            TransferOrder transferOrder = new TransferOrder();
            transferOrder.setTenantCode(memberAccount.getTenantCode());
            transferOrder.setMemberId(memberAccount.getMemberId());
            transferOrder.setMemberRealName(memberRefundApply.getMemberRealName());
            transferOrder.setRefundApplyId(memberRefundApply.getRefundApplyId());
            transferOrder.setOutTradeNo(outTradeNo);
            transferOrder.setAmount(memberRefundApply.getRefundAmount());
            transferOrder.setTransferType("0");
            transferOrder.setPaymentTime(formatter.format(date));
            transferOrder.setRetryTransferNum(1);
            transferOrder.setStatus("1");
            transferOrderService.insertSelective(transferOrder);

            memberAccount.setAccount(memberAccount.getAccount().subtract(memberRefundApply.getRefundAmount()));
            memberAccountService.updateByPrimaryKeySelective(memberAccount);

            MemberAccountRecord memberAccountRecord = new MemberAccountRecord();
            memberAccountRecord.setLocalTradeNo(outTradeNo);
            memberAccountRecord.setTenantCode(memberAccount.getTenantCode());
            memberAccountRecord.setMemberId(memberAccount.getMemberId());
            // 14后台退款)
            memberAccountRecord.setRecordType("14");
            memberAccountRecord.setAmount(memberRefundApply.getRefundAmount());
            memberAccountRecord.setResult(memberAccount.getAccount());
            memberAccountRecord.setRemark("后台退款");
            memberAccountRecordService.insertSelective(memberAccountRecord);
        }
        return TResponse.SUCCESS();
    }

    @Override
    public List<MemberRefundApplyExportVo> exportMemberRefundApply(MemberRefundApplySearch memberRefundApplySearch) {
        return memberRefundApplyMapper.exportMemberRefundApply(memberRefundApplySearch);
    }

    @Override
    public TResponse batchUpdateMemberRefundApplyStuts(Object[] refundApplyAry, String status, String remark, TenantTransfer tenantTransfer, HttpServletRequest request) {
        //遍历转账
        StringBuilder sb = new StringBuilder();
        for (Object o : refundApplyAry) {
            MemberRefundApply memberRefundApply = memberRefundApplyMapper.selectByPrimaryKey(Long.valueOf(String.valueOf(o)));
            Tenant tenant = tenantService.selectByTenantCode(memberRefundApply.getTenantCode());
            MemberInfo memberInfo = memberInfoService.selectByPrimaryKey(memberRefundApply.getMemberId());

            if (!"0".equals(memberRefundApply.getStatus())) {
                sb.append("不能重复审核:" + memberInfo.getMobile()).append(" ");
                continue;
            }

            Date date = new Date();
            //审核状态 0未审核，1审核通过，2审核不通过 默认0
            //审核状态 0未审核，1审核通过，2审核不通过 3提款中 4已到账 默认0
            if ("2".equals(status)) {
                memberRefundApply.setStatus("2");
                memberRefundApply.setLastUpdatedTime(date);
                memberRefundApply.setRemark(remark);
                memberRefundApplyMapper.updateByPrimaryKeySelective(memberRefundApply);
                //return TResponse.SUCCESS();
            }

            if ("1".equals(memberInfo.getStatus())) {
                sb.append("会员被冻结:" + memberInfo.getMobile()).append(" ");
                continue;
                //return TResponse.FAIL("会员已被冻结");
            }

            MemberAccount memberAccount = memberAccountService.selectByPrimaryKey(memberInfo.getMemberId());

            if (memberRefundApply.getRefundAmount().compareTo(memberAccount.getAccount()) > 0) {
                sb.append("会员余额不足以退款:" + memberInfo.getMobile()).append(" ");
                continue;
                //return TResponse.FAIL("会员余额不足以退款");
            }

            long countTransfer = transferOrderService.countFailTransferOrderByMember(memberInfo.getMemberId());
            if (countTransfer > 0) {
                sb.append("会员还有未付款成功的订单:" + memberInfo.getMobile()).append(" ");
                continue;
                //return TResponse.FAIL("会员还有【" + countTransfer + "】笔未付款成功的订单,请稍后再试");
            }

            long countCharging = orderInfoService.countOrderIsCharging(memberInfo.getMemberId());

            if (countCharging > 0) {
                sb.append("会员还有正在充电的订单:" + memberInfo.getMobile()).append(" ");
                continue;
                //return TResponse.FAIL("会员还有正在充电的订单,请稍后再试");
            }

            if (tenantTransfer == null) {
                //默认为手动
                tenantTransfer = new TenantTransfer();
                tenantTransfer.setTransferType("0");
            }

            if ("1".equals(status)) {
                if ("1".equals(tenantTransfer.getTransferType())) {
                    //发起付款
                    WxTransPayWalletVo transPayWalletVo = new WxTransPayWalletVo();

                    TenantSetting tenantSetting = new TenantSetting();

                    //申请来源 0 公众号 1 APP  2小程序 3运营商后台  默认0
                    if ("1".equals(memberRefundApply.getRefundSource())) {
                        TenantPaymentExample tenantPaymentExample = new TenantPaymentExample();
                        tenantPaymentExample.createCriteria().andTenantCodeEqualTo(tenant.getTenantCode()).andPaymentTypeEqualTo("WXPAY");
                        List<TenantPayment> tenantPayments = tenantPaymentService.selectByExample(tenantPaymentExample);

                        if (CollectionUtils.isEmpty(tenantPayments) || StringUtil.isBlank(tenantPayments.get(0).getWxTransferCertPath())) {
                            sb.append("找不到商户证书文件:" + memberInfo.getMobile()).append(" ");
                            continue;
                            //return TResponse.FAIL("找不到商户证书文件");
                        }

                        TransferWays transferWays = transferWaysMapper.selectByPrimaryKey(memberRefundApply.getMemberId());
                        if (transferWays == null) {
                            sb.append("此用户没有绑定信息:" + memberInfo.getMobile()).append(" ");
                            continue;
                            //return TResponse.FAIL("此用户没有绑定信息");
                        }

                        //设置APP退款信息,路径
                        tenantSetting.setWxTransferCertPath(tenantPayments.get(0).getWxTransferCertPath());

                        tenant.setWechatAppid(tenantPayments.get(0).getAppid());
                        tenant.setWechatPayMchid(tenantPayments.get(0).getMchid());
                        tenant.setWechatPaySecret(tenantPayments.get(0).getPrivateKey());

                        memberInfo.setWechatOpenid(transferWays.getWxOpenid());
                    } else {

                        tenantSetting = tenantSettingService.selectByPrimaryKey(tenant.getTenantCode());
                        if (tenantSetting == null || StringUtils.isBlank(tenantSetting.getWxTransferCertPath())) {
                            sb.append("找不到商户证书文件:" + memberInfo.getMobile()).append(" ");
                            continue;
                            //return TResponse.FAIL("找不到商户证书文件");
                        }

                        if (StringUtil.isBlank(memberInfo.getWechatOpenid())) {
                            sb.append("此用户没有绑定微信:" + memberInfo.getMobile()).append(" ");
                            continue;
                            //return TResponse.FAIL("此用户没有绑定微信");
                        }
                    }

                    transPayWalletVo.setRealName(memberRefundApply.getMemberRealName());

                    transPayWalletVo.setAmount(memberRefundApply.getRefundAmount());
                    transPayWalletVo.setMobile(memberInfo.getMobile());

                    //申请单ID
                    if (memberRefundApply != null) {
                        transPayWalletVo.setRefundApplyId(memberRefundApply.getRefundApplyId());
                    }
                    TResponse tResponse = wxPayWalletService.transPayWallet(request, tenant, memberInfo, transPayWalletVo, tenantSetting);
                    if (tResponse.getStatus() != HttpConstant.STATUS_SUCCESS) {
                        sb.append(tResponse.getMessage()).append(" ");
                    }
                    //return tResponse;
                } else if ("0".equals(tenantTransfer.getTransferType())) {
                    memberRefundApply.setStatus("3");
                    memberRefundApply.setLastUpdatedTime(date);
                    memberRefundApplyMapper.updateByPrimaryKeySelective(memberRefundApply);
                    //sb.append("人工转账:").append(memberInfo.getMobile()).append(" ");
                    //return TResponse.SUCCESS();
                } else {
                    sb.append("请设置正确的提现方式").append(" ");
                    continue;
                    //return TResponse.FAIL("请设置正确的提现方式");
                }
            }
        }
        return TResponse.SUCCESS(sb.toString().trim());
    }

    @Override
    public TResponse updateByAliTransfer(TenantUser user, Long memberRefundApplyId, String status, String remark) {
        MemberRefundApply info = memberRefundApplyMapper.selectByPrimaryKey(memberRefundApplyId);
        if (!"1".equals(info.getRefundBy())) {
            return TResponse.FAIL("目前只支持支付宝提现");
        }


        //根据不同的运营商简码生成充值订单号
        String outTradeNo = uidGenerator.genAlipayTransferOutBizNo("4480", CommonConstant.ALIPAY_TRANSFER_PREFIX);

        //1 查询自己余额是否足够
        AlipayFundAccountQueryResponse queryResponse = accountQuery();
        if (queryResponse == null) {
            logger.error("账户余额查询接口异常返回为null");
            return TResponse.FAIL("账户余额查询接口异常");
        }
        if (!queryResponse.isSuccess()) {
            logger.error("账户余额查询接口异常:{}", queryResponse.getBody());
            return TResponse.FAIL("账户余额查询接口异常");
        }

        //账户可用余额，单位元，精确到小数点后两位。示例值：26.45
        logger.warn("appId:" + aliPayConfig.getAppId() + ":账户可用余额:{}元", queryResponse.getAvailableAmount());
        if (info.getFaceAmount().compareTo(new BigDecimal(queryResponse.getAvailableAmount())) > 0) {
            logger.error("账户余额不足,可用余额:{},本次申请转帐金额:{}", queryResponse.getAvailableAmount(), info.getRefundAmount());
            return TResponse.FAIL("账户余额不足");
        }

        info.setLastUpdatedBy(user.getLoginName());
        info.setLastUpdatedTime(new Date());
        info.setAuditingTime(new Date());
        info.setStatus(status);
        info.setOutTradeNo(outTradeNo);
        info.setRemark(remark);
        memberRefundApplyMapper.updateByPrimaryKey(info);

        //生成转帐预订单
        AcctWithdrawOrder acctWithdrawOrder = new AcctWithdrawOrder();
        acctWithdrawOrder.setTenantCode(info.getTenantCode());
        //收款账户类型,0 对公（在金融机构开设的公司账户）,如果银行卡为对公，必须传递省市支行信息或者联行号 1对私（在金融机构开设的个人账户）
        acctWithdrawOrder.setAccountType("1");
        //支付宝的会员ID+真实姓名
        acctWithdrawOrder.setAlipayUserId(info.getAliAcount());
        acctWithdrawOrder.setAlipayUserName(info.getRealName());
        //提现类型 0平台转帐 1网银转帐 默认0
        acctWithdrawOrder.setTransferType("0");
        //申请来源 0运营商后台  默认0
        acctWithdrawOrder.setTransferSource("0");
        acctWithdrawOrder.setTransferBy("0");
        acctWithdrawOrder.setOutTradeNo(outTradeNo);
        acctWithdrawOrder.setWithdrawApplyId(info.getRefundApplyId());//申请单ID
        acctWithdrawOrder.setAmount(info.getFaceAmount());//单位（元）
        //到帐状态 0未到帐  1已到帐 2转账失败 默认0
        acctWithdrawOrder.setStatus("0");
        acctWithdrawOrder.setCreatedTime(new Date());
        acctWithdrawOrderService.insertSelectiveReturnId(acctWithdrawOrder);


        try {
            // 2 创建AlipayClient实例
            AlipayClient alipayClient = new DefaultAlipayClient(assembleClientParams());
            // 3 创建使用的Open API对应的Request请求对象
            AlipayFundTransUniTransferRequest uniTransferRequest = uniTransfer(outTradeNo, info);
            // 4 发起请求并处理响应
            AlipayFundTransUniTransferResponse transferResponse = alipayClient.certificateExecute(uniTransferRequest);

            //如果转账接口同步返回的 status 属性为 SUCCESS 则表示转账成功；同步调用若发生超时等异常情况，可以通过异步通知或者调用转账查询接口做主动查询
            if (!transferResponse.isSuccess()) {
                logger.error("支付宝转账失败:{},:{},:{}", transferResponse.getMsg(), transferResponse.getSubMsg(), transferResponse.getBody());
                info.setRemark(transferResponse.getMsg());
                info.setStatus("5");
                memberRefundApplyMapper.updateByPrimaryKey(info);
                return TResponse.FAIL("支付宝转账失败," + transferResponse.getSubMsg());
            }

            //6 查转账单据状态
            AlipayFundTransCommonQueryResponse commonQueryResponse = queryTransferInfo(assembleClientParams(), transferResponse);
            if (commonQueryResponse == null ) {
                logger.error("查帐接口异常返回为null");
                return TResponse.FAIL("查帐接口异常");
            }

            if (!commonQueryResponse.isSuccess()) {
                logger.error("查帐接口异常:{},:{},:{}", commonQueryResponse.getMsg(), commonQueryResponse.getSubMsg(), commonQueryResponse.getBody());
                return TResponse.FAIL("查帐接口异常");
            }

            //转账单据状态
            if (commonQueryResponse.getStatus().equals("SUCCESS")) {
                logger.info("支付宝转账成功，准备入账:{}", info.getFaceAmount());

                //7 入帐
                acctWithdrawOrderService.updateSuccessByTransfer(transferResponse, acctWithdrawOrder.getWithdrawOrderId(), info.getRefundApplyId());
            }

            logger.info("支付宝转帐成功:{},info.id:{}", info.getRefundAmount(), memberRefundApplyId);


            TResponse tResponse = TResponse.SUCCESS("转帐成功");
            tResponse.put(acctWithdrawOrder);
            return tResponse;


        } catch (Exception e) {
            e.printStackTrace();
        }


        return null;
    }

    @Override
    public MemberRefundApply selectByOutOrderNo(String outOrderNo) {
        MemberRefundApplyExample example = new MemberRefundApplyExample();
        example.createCriteria().andOutTradeNoEqualTo(outOrderNo);
        return memberRefundApplyMapper.selectByExample(example).stream().findFirst().orElseGet(() -> null);
    }


    public AlipayFundAccountQueryResponse accountQuery() {
        try {
            CertAlipayRequest certAlipayRequest = assembleClientParams();

            DefaultAlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
            AlipayFundAccountQueryRequest request = new AlipayFundAccountQueryRequest();

            //request.setBizContent("{" +
            //        "\"alipay_user_id\":\"208818457777488333\"," +
            //        "\"account_type\":\"ACCTRANS_ACCOUNT\"" +
            //        "  }");

            AlipayFundAccountQueryModel model = new AlipayFundAccountQueryModel();
            //在沙箱环境下商户UID即为PID
            //在沙箱环境下是商户UID2088102168917625
            //model.setAlipayUserId("2088102168917625");
            //支付方的支付宝帐号,必须等于请求发起方PID
            //model.setAlipayUserId("2088102168917625");
            model.setAlipayUserId(aliPayConfig.getAlipayUserId());

            //查询的账号类型，固定值为 ACCTRANS_ACCOUNT。
            model.setAccountType("ACCTRANS_ACCOUNT");
            request.setBizModel(model);

            return alipayClient.certificateExecute(request);
        } catch (Exception e) {
            logger.error("账户余额查询接口alipay.fund.account.query 异常", e);
            return null;
        }
    }


    /**
     * 支付宝配置
     *
     * @return
     */
    private CertAlipayRequest assembleClientParams() {

        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        //设置网关地址
        certAlipayRequest.setServerUrl(aliPayConfig.getServerUrl());
        //设置应用Id
        certAlipayRequest.setAppId(aliPayConfig.getAppId());

        //设置PKCS8格式的应用私钥
        //certAlipayRequest.setPrivateKey(aliPayConfig.getPrivateKey());
        certAlipayRequest.setPrivateKey(aliPayConfig.getPrivateKey());

        //设置请求格式，固定值json
        certAlipayRequest.setFormat(aliPayConfig.getFormat());
        //设置字符集
        certAlipayRequest.setCharset(aliPayConfig.getCharset());
        //设置签名类型
        certAlipayRequest.setSignType(aliPayConfig.getSignType());

        //如果是生产环境或者预演环境，则使用代理模式
        //if ("prod".equals(activeEnv) || "stage".equals(activeEnv) || "test".equals(activeEnv)) {
        //设置应用公钥证书路径
        certAlipayRequest.setCertPath(aliPayConfig.getCertPath());
        //设置支付宝公钥证书路径
        certAlipayRequest.setAlipayPublicCertPath(aliPayConfig.getPublicCertPath());
        //设置支付宝根证书路径
        certAlipayRequest.setRootCertPath(aliPayConfig.getRootCertPath());

        return certAlipayRequest;
    }

    /**
     * 转账请求入参
     * https://opendocs.alipay.com/open/309/106236
     *
     * @return
     */
    private AlipayFundTransUniTransferRequest uniTransfer(String outTradeNo, MemberRefundApply info) {
        // 初始化Request，并填充Model属性。实际调用时请替换为您想要使用的API对应的Request对象。
        AlipayFundTransUniTransferRequest bizQueryRequest = new AlipayFundTransUniTransferRequest();

        //转账参数
        AlipayFundTransPayModel model = new AlipayFundTransPayModel();
        model.setOutBizNo(outTradeNo);//商户端的唯一订单号，对于同一笔转账请求，商户需保证该订单号唯一
        model.setTransAmount(String.valueOf(info.getFaceAmount()));//订单总金额，单位为元，精确到小数点后两位，取值范围[0.1,100000000]。

        model.setProductCode("TRANS_ACCOUNT_NO_PWD");//销售产品码。单笔无密转账固定为 TRANS_ACCOUNT_NO_PWD。
        model.setBizScene("DIRECT_TRANSFER");//业务场景。单笔无密转账固定为 DIRECT_TRANSFER。

        String title = info.getRemark();

        //收款方信息
        Participant participant = new Participant();

        //参与方的标识类型，目前支持如下枚举：
        //ALIPAY_USER_ID：支付宝的会员 ID。
        //ALIPAY_LOGON_ID：支付宝登录号，支持邮箱和手机号格式。
        //TODO 生产环境使用
//        participant.setIdentityType("ALIPAY_USER_ID");
        //买家USER_ID
        participant.setIdentity(info.getAliAcount());

        //沙箱环境下找不到买家USER_ID，只能使用ALIPAY_LOGON_ID类型
//        participant.setIdentityType("ALIPAY_LOGON_ID");
//        participant.setIdentity("hpccbd3956@sandbox.com");

        participant.setIdentityType("ALIPAY_LOGON_ID");
//        participant.setIdentity("455322144@qq.com");

        //参与方真实姓名。如果非空，将校验收款支付宝账号姓名一致性。当 identity_type=ALIPAY_LOGON_ID 时，本字段必填
//        participant.setName("张文博");
        participant.setName(info.getRealName());
        model.setPayeeInfo(participant);

        model.setOrderTitle(title);//转账业务的标题，用于在支付宝用户的账单里显示
        model.setRemark(title);//业务备注

        bizQueryRequest.setBizModel(model);
        return bizQueryRequest;
    }


    public AlipayFundTransCommonQueryResponse queryTransferInfo(CertAlipayRequest certAlipayRequest, AlipayFundTransUniTransferResponse transferResponse) {
        try {
            DefaultAlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
            AlipayFundTransCommonQueryRequest request = new AlipayFundTransCommonQueryRequest();

            //request.setBizContent("{" +
            //        "\"product_code\":\"TRANS_ACCOUNT_NO_PWD\"," +
            //        "\"biz_scene\":\"DIRECT_TRANSFER\"," +
            //        "\"out_biz_no\":\"20190619000000001\"," +
            //        "\"order_id\":\"20190619110070000006800000025890\"" +
            //        "  }");

            AlipayFundTransCommonQueryModel model = new AlipayFundTransCommonQueryModel();

            model.setOrderId(transferResponse.getOrderId());
            model.setPayFundOrderId(transferResponse.getPayFundOrderId());
            model.setOutBizNo(transferResponse.getOutBizNo());

            //描述特定的业务场景，如果传递了out_biz_no 则该字段为必传。单笔无密转账固定为 DIRECT_TRANSFER。
            model.setBizScene("DIRECT_TRANSFER");

            //销售产品码，如果传了 out_biz_no，则该字段必传。单笔无密转账固定为 TRANS_ACCOUNT_NO_PWD。
            model.setProductCode("TRANS_ACCOUNT_NO_PWD");

            request.setBizModel(model);
            return alipayClient.certificateExecute(request);
        } catch (Exception e) {
            logger.error("单据查询接口 alipay.fund.trans.common.query 异常", e);
        }

        return null;
    }

}

